import Footer from "./components/Footer"
import TodoList from "./components/TodoList"
const {
    createElement: h,
    useState,
    useEffect
} = React
import {
    useLocalStorage
} from './storage'

let id = 0
const storage = useLocalStorage('__TODO_REACT')

const filters = {
    all: function (todos) {
        return todos
    },
    active: function (todos) {
        return todos.filter(function (todo) {
            return !todo.completed;
        })
    },
    completed: function (todos) {
        return todos.filter(function (todo) {
            return todo.completed
        })
    }
}

function App() {
    const data = storage.get() || []
    const [word, setWord] = useState('')
    const [todos, setTodos] = useState(data)
    const [visibility, setVisibility] = useState(window.location.hash.slice(2) || 'all')
    const [remainingCount, setRemainingCount] = useState(filters.active(todos).length)
    const [filteredTodos, setFilteredTodos] = useState(filters[visibility](todos))

    id = todos[0] ? todos[0].id : 0
    window.addEventListener('hashchange', () => {
        if (window.location.hash) {
            setVisibility(window.location.hash.slice(2) || 'all')
        } else {
            setVisibility('all')
        }
    })
    const addTodo = () => {
        setTodos([{
            id: ++id,
            completed: false,
            text: word
        }, ...todos])
        setWord('')
    }

    useEffect(() => {
        setRemainingCount(filters.active(todos).length)
        storage.save(todos)
    }, [todos])

    useEffect(() => {
        setFilteredTodos(filters[visibility](todos))
    }, [visibility, todos])

    const changeTodo = (todo, newTodo) => {
        const index = todos.indexOf(todo)
        todos[index]= newTodo
        setTodos([...todos])
    }

    const removeToto = (todo) => {
        const index = todos.indexOf(todo)
        todos.splice(index, 1)
        setTodos([...todos])
    }

    const toggleAll = (e) => {
        todos.forEach(todo => {
            todo.completed = e.target.checked
        })
        setTodos([...todos])
    }
    const clearCompleted = () => {
        setTodos([...filters.active(todos)])
    }

    return h(React.Fragment, null,
        h('section', {
                className: 'todoapp'
            },
            h('header', {
                    className: 'header'
                },
                h('h1', null, 'todos'),
                h('input', {
                    className: 'new-todo',
                    autoFocus: 'autofocus',
                    placeholder: 'What needs to be done?',
                    value: word,
                    onInput(e) {
                        setWord(e.target.value)
                    },
                    onKeyDown(e) {
                        if (e.code === 'Enter' || e.keyCode === 13) {
                            addTodo()
                        }
                    }
                })
            ),
            h('section', {
                    className: 'main'
                },
                h('input', {
                    type: 'checkbox',
                    id: 'toggle-all',
                    className: 'toggle-all',
                    onChange:toggleAll,
                    checked: remainingCount === 0 ? true : false
                }),
                h('label', {
                    htmlFor: 'toggle-all'
                }, 'Mark all as complete'),
                h(TodoList, {
                    todos: filteredTodos,
                    removeToto,
                    changeTodo
                }),
                h('footer', {
                        className: 'footer',
                        style:{
                            display: todos.length?'':'none'
                        }
                    },
                    h('span', {
                        className: 'todo-count'
                    }, h('strong', null, remainingCount), ' item left'),
                    h('ul', {
                        className: 'filters'
                    }, ['all', 'active', 'completed'].map((item) => {
                        return h('li', {
                            key: item
                        }, h('a', {
                            href: `#/${item}`,
                            className: visibility === item ? 'selected' : ''
                        }, `${item.slice(0,1).toUpperCase()}${item.slice(1)}`))
                    })),
                    h('button', {
                        className: 'clear-completed',
                        onClick: clearCompleted
                    }, 'Clear completed')
                )
            )
        ),
        h(Footer)
    )
}

ReactDOM.render(
    h(App),
    document.getElementById('app')
)